Imports MetaView.AnnotatedImage
Imports System.Reflection
Friend Class AnnotationsManager
  Inherits System.Windows.Forms.Form
    Private bUISelectEvent As Boolean = False, bBuildingTree As Boolean = False

    Private WithEvents oAnnotatedImage As AnnotatedImage

#Region " Windows Form Designer generated code "

    Public Sub New(ByVal oAnnotatedImage As AnnotatedImage)
        MyBase.New()

        'This call is required by the Windows Form Designer.
        InitializeComponent()

        'Add any initialization after the InitializeComponent() call
        Me.oAnnotatedImage = oAnnotatedImage
        AddHandler Me.Closing, AddressOf Me.CancelClose

        CreateAndShowAnnotationsTree()
    End Sub

    'Cancel close event handler
    Protected Sub CancelClose(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs)
        'Do not close but hide
        Me.Visible = False
        e.Cancel = True
    End Sub

    'Form overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    Friend WithEvents AnnotationsTree As System.Windows.Forms.TreeView
    Friend WithEvents Icons As System.Windows.Forms.ImageList
    Friend WithEvents ctxAnnotation As System.Windows.Forms.ContextMenu
    Friend WithEvents ctxAnnotationContainer As System.Windows.Forms.ContextMenu
    Friend WithEvents menuDeleteAnnotation As System.Windows.Forms.MenuItem
    Friend WithEvents menuAnnotationProperties As System.Windows.Forms.MenuItem
    Friend WithEvents menuAnnotationContainerProperties As System.Windows.Forms.MenuItem
    Friend WithEvents ctxAnnotations As System.Windows.Forms.ContextMenu
    Friend WithEvents menuNewAnnotationContainer As System.Windows.Forms.MenuItem
    Friend WithEvents menuDeleteAnnotationContainers As System.Windows.Forms.MenuItem
    Friend WithEvents menuDeleteAnnotationContainer As System.Windows.Forms.MenuItem
    Friend WithEvents mnuShowPoints As System.Windows.Forms.MenuItem
    Friend WithEvents menuNewAnnotation As System.Windows.Forms.MenuItem
    Friend WithEvents menuNewAnnotationInDefaultContainer As System.Windows.Forms.MenuItem
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.components = New System.ComponentModel.Container
        Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(AnnotationsManager))
        Me.AnnotationsTree = New System.Windows.Forms.TreeView
        Me.Icons = New System.Windows.Forms.ImageList(Me.components)
        Me.ctxAnnotation = New System.Windows.Forms.ContextMenu
        Me.menuAnnotationProperties = New System.Windows.Forms.MenuItem
        Me.menuDeleteAnnotation = New System.Windows.Forms.MenuItem
        Me.ctxAnnotationContainer = New System.Windows.Forms.ContextMenu
        Me.menuNewAnnotation = New System.Windows.Forms.MenuItem
        Me.menuAnnotationContainerProperties = New System.Windows.Forms.MenuItem
        Me.menuDeleteAnnotationContainer = New System.Windows.Forms.MenuItem
        Me.ctxAnnotations = New System.Windows.Forms.ContextMenu
        Me.menuNewAnnotationContainer = New System.Windows.Forms.MenuItem
        Me.menuNewAnnotationInDefaultContainer = New System.Windows.Forms.MenuItem
        Me.mnuShowPoints = New System.Windows.Forms.MenuItem
        Me.menuDeleteAnnotationContainers = New System.Windows.Forms.MenuItem
        Me.SuspendLayout()
        '
        'AnnotationsTree
        '
        Me.AnnotationsTree.BorderStyle = System.Windows.Forms.BorderStyle.None
        Me.AnnotationsTree.HideSelection = False
        Me.AnnotationsTree.ImageIndex = 0
        Me.AnnotationsTree.ImageList = Me.Icons
        Me.AnnotationsTree.Location = New System.Drawing.Point(0, 0)
        Me.AnnotationsTree.Name = "AnnotationsTree"
        Me.AnnotationsTree.SelectedImageIndex = 0
        Me.AnnotationsTree.Size = New System.Drawing.Size(164, 281)
        Me.AnnotationsTree.TabIndex = 0
        '
        'Icons
        '
        Me.Icons.ImageStream = CType(resources.GetObject("Icons.ImageStream"), System.Windows.Forms.ImageListStreamer)
        Me.Icons.TransparentColor = System.Drawing.Color.Transparent
        Me.Icons.Images.SetKeyName(0, "")
        Me.Icons.Images.SetKeyName(1, "")
        Me.Icons.Images.SetKeyName(2, "")
        Me.Icons.Images.SetKeyName(3, "")
        '
        'ctxAnnotation
        '
        Me.ctxAnnotation.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.menuAnnotationProperties, Me.menuDeleteAnnotation})
        '
        'menuAnnotationProperties
        '
        Me.menuAnnotationProperties.Index = 0
        Me.menuAnnotationProperties.Text = "Properties"
        '
        'menuDeleteAnnotation
        '
        Me.menuDeleteAnnotation.Index = 1
        Me.menuDeleteAnnotation.Text = "Delete"
        '
        'ctxAnnotationContainer
        '
        Me.ctxAnnotationContainer.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.menuNewAnnotation, Me.menuAnnotationContainerProperties, Me.menuDeleteAnnotationContainer})
        '
        'menuNewAnnotation
        '
        Me.menuNewAnnotation.Index = 0
        Me.menuNewAnnotation.Text = "New ROI"
        '
        'menuAnnotationContainerProperties
        '
        Me.menuAnnotationContainerProperties.Index = 1
        Me.menuAnnotationContainerProperties.Text = "Properties"
        '
        'menuDeleteAnnotationContainer
        '
        Me.menuDeleteAnnotationContainer.Index = 2
        Me.menuDeleteAnnotationContainer.Text = "Delete"
        '
        'ctxAnnotations
        '
        Me.ctxAnnotations.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.menuNewAnnotationContainer, Me.menuNewAnnotationInDefaultContainer, Me.mnuShowPoints, Me.menuDeleteAnnotationContainers})
        '
        'menuNewAnnotationContainer
        '
        Me.menuNewAnnotationContainer.Index = 0
        Me.menuNewAnnotationContainer.Text = "New ROI-GROUP"
        '
        'menuNewAnnotationInDefaultContainer
        '
        Me.menuNewAnnotationInDefaultContainer.Index = 1
        Me.menuNewAnnotationInDefaultContainer.Text = "New ROI in default GROUP"
        '
        'mnuShowPoints
        '
        Me.mnuShowPoints.Index = 2
        Me.mnuShowPoints.Text = "Show Points"
        '
        'menuDeleteAnnotationContainers
        '
        Me.menuDeleteAnnotationContainers.Index = 3
        Me.menuDeleteAnnotationContainers.Text = "Delete all ROI-GROUPS"
        '
        'AnnotationsManager
        '
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.ClientSize = New System.Drawing.Size(165, 281)
        Me.Controls.Add(Me.AnnotationsTree)
        Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow
        Me.Location = New System.Drawing.Point(500, 0)
        Me.Name = "AnnotationsManager"
        Me.ShowInTaskbar = False
        Me.StartPosition = System.Windows.Forms.FormStartPosition.Manual
        Me.Text = "ROI Manager"
        Me.ResumeLayout(False)

    End Sub

#End Region

    Protected Overrides Sub Finalize()
        MyBase.Finalize()
        oAnnotatedImage = Nothing
    End Sub

    Private Sub CreateAndShowAnnotationsTree()
        'Show all objects in the annotatedImage. We dont want to generate select events when creating the
        'tree, so we set bBuildingTree

        If Me.Visible Then
            Dim oSelectedItem As Object = Me.oAnnotatedImage.SelectedItem
            Debug.WriteLine("Creating and drawing annotations treeview", "ShowAnnotationsTree")
            Me.bBuildingTree = True
            Try
                Me.AnnotationsTree.AllowDrop = True
                Me.AnnotationsTree.BeginUpdate()
                Me.AnnotationsTree.Nodes.Clear()
                Dim oRootNode As New TreeNode("ROI Groups")
                oRootNode.SelectedImageIndex = 2
                oRootNode.ImageIndex = 2
                Me.AnnotationsTree.ShowRootLines = False
                Me.AnnotationsTree.Nodes.Add(oRootNode)

                Dim oAnnContainer As AnnotationContainer
                For Each oAnnContainer In Me.oAnnotatedImage.AnnotationContainers
                    Dim oContainerNode As New TreeNode(oAnnContainer.Key)
                    oContainerNode.Tag = oAnnContainer
                    oContainerNode.ImageIndex = 1
                    oContainerNode.SelectedImageIndex = 1
                    If Object.Equals(oSelectedItem, oAnnContainer) Then Me.AnnotationsTree.SelectedNode = oContainerNode

                    oRootNode.Nodes.Add(oContainerNode)

                    Dim oAnn As Annotation
                    For Each oAnn In oAnnContainer.Annotations
                        Dim oAnnNode As New TreeNode(oAnn.Key)
                        oAnnNode.Tag = oAnn
                        oContainerNode.Nodes.Add(oAnnNode)
                        If Object.Equals(oSelectedItem, oAnn) Then Me.AnnotationsTree.SelectedNode = oAnnNode

                        If Me.mnuShowPoints.Checked = True Then
                            'Show the points too
                            Dim i As Integer
                            For i = 0 To oAnn.Points.Count - 1
                                Dim oPtNode As New TreeNode(i & ": " & oAnn.Points.Item(i).X & "," & oAnn.Points.Item(i).Y)
                                oPtNode.ImageIndex = 3
                                oPtNode.SelectedImageIndex = 3
                                oAnnNode.Nodes.Add(oPtNode)
                            Next
                        End If
                    Next

                Next
                oRootNode.ExpandAll()

                Me.AnnotationsTree.EndUpdate()
            Catch ex As Exception

            End Try
            Me.bBuildingTree = False
        Else
            Debug.WriteLine("Treeview not visible, skipping", "ShowAnnotationsTree")
        End If
    End Sub

#Region "Annotated Image events"

    Private Sub oAnnotatedImage_AnnotationsChanged(ByVal sender As Object) Handles oAnnotatedImage.AnnotationsChanged
        'Refresh control
        If oAnnotatedImage.Updating = False Then CreateAndShowAnnotationsTree()
    End Sub

    Private Sub oAnnotatedImage_AnnotationItemSelected(ByVal objAnnotation As Object) Handles oAnnotatedImage.AnnotationItemSelected
        'Refresh control ...Not very effcient but easy
        Debug.WriteLine("AnnotationManager.AnnotationItemSelected")
        If Me.bUISelectEvent = False Then
            'Only display if event does not come from local UI
            CreateAndShowAnnotationsTree()
        End If
    End Sub
#End Region

    Private Sub AnnotationsTree_AfterSelect(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles AnnotationsTree.AfterSelect
        If Me.bBuildingTree = False Then
            Me.bUISelectEvent = True
            Dim oNode As TreeNode = e.Node
            If TypeOf oNode.Tag Is Annotation Then
                Dim oAnn As Annotation = CType(oNode.Tag, Annotation)
                Debug.WriteLine("Selecting annotation " & oAnn.Key, "AnnotationsTree.AfterSelect")
                Me.oAnnotatedImage.SelectedItem = oAnn  'This will trigger the event oAnnotatedImage_AnnotationSelected!!!
                Me.oAnnotatedImage.Draw()
            ElseIf TypeOf oNode.Tag Is AnnotationContainer Then
                Dim oAnnContainer As AnnotationContainer = CType(oNode.Tag, AnnotationContainer)
                Debug.WriteLine("Selecting annotation container " & oAnnContainer.Key, "AnnotationsTree.AfterSelect")
                Me.oAnnotatedImage.SelectedItem = oAnnContainer
                Me.oAnnotatedImage.Draw()
            Else
                'Deselect all?
            End If
            Me.bUISelectEvent = False
        Else
            Debug.WriteLine("Canceling event because of treeview rebuild ...", "AnnotationsTree.AfterSelect")
        End If
    End Sub

    Private Sub AnnotationsTree_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles AnnotationsTree.MouseDown
        'Show context menu if right mouse
        If e.Button = Windows.Forms.MouseButtons.Right Then

            Dim oNode As TreeNode = Me.AnnotationsTree.GetNodeAt(e.X, e.Y)

            'Make sure it is selected!
            Me.AnnotationsTree.SelectedNode = oNode
            If Not oNode Is Nothing Then
                If TypeOf oNode.Tag Is Annotation Then
                    Me.ctxAnnotation.Show(Me, New Point(e.X, e.Y))
                ElseIf TypeOf oNode.Tag Is AnnotationContainer Then
                    Me.ctxAnnotationContainer.Show(Me, New Point(e.X, e.Y))
                Else
                    Me.ctxAnnotations.Show(Me, New Point(e.X, e.Y))
                End If
            End If
        End If
    End Sub

    Private Sub AnnotationsManager_Activated(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Activated
        'Only enable if there is a bitmap!
        Debug.WriteLine("AnnotationsManager is activated")
        If Not Me.oAnnotatedImage.BitmapPresent Then
            Me.AnnotationsTree.Enabled = False
        Else
            Me.AnnotationsTree.Enabled = True
        End If
    End Sub

#Region "Menu event handlers"
    Private Sub menuAnnotationProperties_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles menuAnnotationProperties.Click
        Me.oAnnotatedImage.SetAnnotationProperties(CType(Me.AnnotationsTree.SelectedNode.Tag, Annotation))
    End Sub

    Private Sub AnnotationsTree_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles AnnotationsTree.DoubleClick
        If TypeOf Me.AnnotationsTree.SelectedNode.Tag Is Annotation Then
            Me.oAnnotatedImage.SetAnnotationProperties(CType(Me.AnnotationsTree.SelectedNode.Tag, Annotation))
        ElseIf TypeOf Me.AnnotationsTree.SelectedNode.Tag Is AnnotationContainer Then
            Me.oAnnotatedImage.SetAnnotationContainerProperties(CType(Me.AnnotationsTree.SelectedNode.Tag, AnnotationContainer))
        End If
    End Sub

    Private Sub menuDeleteAnnotation_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles menuDeleteAnnotation.Click
        Debug.WriteLine("menuDeleteAnnotation_Click")
        Me.oAnnotatedImage.DeleteAnnotation(Me, CType(Me.AnnotationsTree.SelectedNode.Tag, Annotation))
    End Sub

    Private Sub menuNewAnnotation_Click1(ByVal sender As Object, ByVal e As System.EventArgs) Handles menuNewAnnotation.Click
        Debug.WriteLine("MenuNewAnnotationManual_Click")
        Me.oAnnotatedImage.CreateNewAnnotation(CType(Me.AnnotationsTree.SelectedNode.Tag, AnnotationContainer))
    End Sub

    Private Sub menuAnnotationContainerProperties_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles menuAnnotationContainerProperties.Click
        Me.oAnnotatedImage.SetAnnotationContainerProperties(CType(Me.AnnotationsTree.SelectedNode.Tag, AnnotationContainer))
    End Sub

    Private Sub menuDeleteAnnotationContainers_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles menuDeleteAnnotationContainers.Click
        Me.oAnnotatedImage.DeleteAllAnnotationContainers(Me)
    End Sub

    Private Sub menuNewAnnotationContainer_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles menuNewAnnotationContainer.Click
        Debug.WriteLine("MenuNewAnnotationContainer_Click")
        Me.oAnnotatedImage.CreateNewAnnotationContainer()
    End Sub

    Private Sub menuDeleteAnnotationContainer_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles menuDeleteAnnotationContainer.Click
        Me.oAnnotatedImage.DeleteAnnotationContainer(Me, CType(Me.AnnotationsTree.SelectedNode.Tag, AnnotationContainer))
    End Sub

    Private Sub menuNewAnnotationInDefaultContainer_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles menuNewAnnotationInDefaultContainer.Click
        'Create new annotation in default container
        Debug.WriteLine("MenuNewAnnotationIndefaultContainer_Click")
        Me.oAnnotatedImage.CreateNewAnnotationInDefaultContainer()
    End Sub

#End Region

    Private Sub mnuShowPoints_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuShowPoints.Click
        mnuShowPoints.Checked = Not mnuShowPoints.Checked
        CreateAndShowAnnotationsTree()
    End Sub

    Private Sub AnnotationsTree_ItemDrag(ByVal sender As Object, ByVal e As System.Windows.Forms.ItemDragEventArgs) Handles AnnotationsTree.ItemDrag
        Dim oDraggedNode As TreeNode = CType(e.Item, TreeNode)

        If TypeOf oDraggedNode.Tag Is Annotation Then
            DoDragDrop(e.Item, DragDropEffects.Move)
        Else
            DoDragDrop(e.Item, DragDropEffects.None)
        End If
    End Sub

    Private Sub AnnotationsTree_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles AnnotationsTree.DragDrop
        'Convert from Form Coordinates to treeView Client coordinates
        Dim oPos As Point = Me.AnnotationsTree.PointToClient(New Point(e.X, e.Y))

        'Find the node at this position
        Dim oDropNode As TreeNode = Me.AnnotationsTree.GetNodeAt(oPos)

        If TypeOf oDropNode.Tag Is AnnotationContainer Then
            'change container annotation
            Dim oAnnContainer As AnnotationContainer = CType(oDropNode.Tag, AnnotationContainer)

            Dim oSrcNode As TreeNode = CType(e.Data.GetData("System.Windows.Forms.TreeNode"), TreeNode)
            Dim oAnn As Annotation = CType(oSrcNode.Tag, Annotation)

            'Remove itself from its parent container
            oAnn.AnnotationContainer.Annotations.Remove(oAnn.Key)

            'Add to other container
            oAnnContainer.Annotations.Add(oAnn, oAnn.Key)

            CreateAndShowAnnotationsTree()
        End If
    End Sub

    Private Sub AnnotationsTree_DragOver(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles AnnotationsTree.DragOver
        'Convert from Form Coordinates to treeView Client coordinates
        Dim oPos As Point = Me.AnnotationsTree.PointToClient(New Point(e.X, e.Y))

        'Find the node at this position
        Dim oDropNode As TreeNode = Me.AnnotationsTree.GetNodeAt(oPos)
        If TypeOf oDropNode.Tag Is AnnotationContainer Then
            e.Effect = DragDropEffects.Move
        Else
            e.Effect = DragDropEffects.None
        End If
    End Sub

    Private Sub AnnotationsManager_VisibleChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.VisibleChanged
        If Me.Visible = True Then
            CreateAndShowAnnotationsTree()
        End If
    End Sub



End Class
